package com.ssy.jt808.gateway.client.http;

import com.ssy.jt808.gateway.client.exception.JtGatewayRequestException;
import com.ssy.jt808.gateway.client.pojo.JtRequestBase;
import com.ssy.jt808.gateway.client.pojo.JtResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Objects;

/**
 * @author zeno
 */
@Component
public class JtHttpClient{

  private static final String SUCCESS_CODE = "200";

  private RestTemplate restTemplate;

  public JtHttpClient(){ }

  public <R> R request( JtRequestBase request ){
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<JtRequestBase> entity = new HttpEntity<>(request, headers);

    ResponseEntity<JtResponse<R>> response = restTemplate.exchange(request.url(),
                                                                   request.method(),
                                                                   entity,
                                                                   request.replyTypeRef());
    JtResponse<R> jtResponse = response.getBody();
    if( jtResponse == null ){
      throw new JtGatewayRequestException(this.getClass() + ".request(..) 响应数据不正确");
    }

    if( !Objects.equals(jtResponse.getCode(), SUCCESS_CODE) ){
      HttpStatus httpStatus = HttpStatus.valueOf(Integer.parseInt(jtResponse.getCode()));
      throw new JtGatewayRequestException(httpStatus, jtResponse.getMsg());
    }

    return jtResponse.getData();
  }

  @Autowired
  public void setRestTemplate( RestTemplate restTemplate ){
    this.restTemplate = restTemplate;
  }
}
